package com.jacen.etl.action;

import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jodd.util.StringUtil;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jacen.etl.entity.EtlDependentEntity;
import com.jacen.etl.entity.EtlEntity;
import com.jacen.etl.entity.EtlScriptEntity;
import com.jacen.etl.services.EtlDependentService;
import com.jacen.etl.services.EtlScriptService;
import com.jacen.etl.services.EtlService;
import com.jacen.etl.services.ServiceProxyFactory;
import com.jacen.etl.util.HttpParamCaster;
import com.jacen.etl.util.ServletUtils;
import com.jacen.etl.util.Utils;

public class EtlManagerAction {

	private EtlService service = ServiceProxyFactory.createProxy(EtlService.class);
	private EtlScriptService scriptService = ServiceProxyFactory.createProxy(EtlScriptService.class);
	private EtlDependentService dependentService = ServiceProxyFactory.createProxy(EtlDependentService.class);
	private static final Logger logger = LoggerFactory.getLogger(EtlManagerAction.class);
	public static String ETL_ENTITY = "etlEntity";

	/**
	 * 分页查询
	 * @param request
	 * @param response
	 * @throws ServletException IOException
	 */
	public void getPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
		String entitySchema = HttpParamCaster.getUTF8Parameter(request, "entitySchema");
		String entityName = HttpParamCaster.getUTF8Parameter(request, "entityName");
		String runCycle = HttpParamCaster.getUTF8Parameter(request, "runCycle");
		String runEnable = HttpParamCaster.getUTF8Parameter(request, "runEnable");
		
		int page = HttpParamCaster.getIntParameter(request, "page", 1);
		int size = HttpParamCaster.getIntParameter(request, "size",Utils.PAGE_SIZE);
		Map<String, Object> mapParams = new HashMap<String, Object>();
		Map<Long, String> scritpNum = new HashMap<Long, String>();
		Map<Long, String> depNum = new HashMap<Long, String>();
		mapParams.put("entitySchema", entitySchema);
		mapParams.put("entityName", entityName);
		mapParams.put("runCycle", runCycle);
		mapParams.put("runEnable", runEnable);
		
		try {
			List<EtlEntity> list = service.getPage(mapParams, page, size);
			long count = service.getCount(mapParams);
			long totalpage = (count/size) + ((count%size) == 0 ? 0 : 1);
			
			for(EtlEntity entity : list){
				long num = scriptService.getCount(entity.getEntityId());
				scritpNum.put(entity.getEntityId().longValue(), String.valueOf(num));
				num = dependentService.getCount(entity.getEntityId());
				depNum.put(entity.getEntityId().longValue(),  String.valueOf(num));
			}
			
			request.setAttribute("entitySchema", entitySchema);
			request.setAttribute("entityName", entityName);
			request.setAttribute("runCycle", runCycle);
			request.setAttribute("runEnable", runEnable);
			request.setAttribute("list", list);
			request.setAttribute("count", count);
			request.setAttribute("page", page);
			request.setAttribute("size", size);
			request.setAttribute("totalpage", totalpage);
			request.setAttribute("scritpNum", scritpNum);
			request.setAttribute("depNum", depNum);
		} catch (Exception e) {
			logger.error("获取EtlEntity列表失败", e);
			request.setAttribute("error", e.getMessage());
			request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
			return;
		}
		request.getRequestDispatcher("/jsp/etl/list.jsp").forward(request, response);
	}
	
		/**
		 * 新增
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException 
		 * @throws ServletException 
		 */
		public void insert(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			String message ="";
			EtlEntity entity = new EtlEntity();
			try {
				if (request.getMethod().equalsIgnoreCase("get")) {
					String size = HttpParamCaster.getUTF8Parameter(request, "size");
					request.setAttribute("size", Integer.valueOf(size));
					request.getRequestDispatcher("/jsp/etl/insert.jsp").forward(request, response);
					return;
				}
				entity = ServletUtils.getEntity(request, EtlEntity.class);
				
				if(service.getEntityBySchemaAndName(entity.getEntitySchema(), entity.getEntityName())!=null){
					String size = HttpParamCaster.getUTF8Parameter(request, "size");
					request.setAttribute("size", Integer.valueOf(size));
					message = "{'code':0,'message':'实例已存在'}";
					ServletUtils.outputHTML(response,message);
					return;
				}
				
				entity.setCreateDate(new Timestamp(System.currentTimeMillis()));
				service.insert(entity);
			} catch (Exception e) {
				e.printStackTrace();
				message = "{'code':0,'message':'新增失败'}";
				ServletUtils.outputHTML(response,message);
				return;
			}
			message = "{'code':1,'message':'新增成功'}";
			ServletUtils.outputHTML(response,message);
		}
		
		/**
		 * 修改
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException 
		 * @throws ServletException 
		 */
		public void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
			try {
				String id = HttpParamCaster.getUTF8Parameter(request, "entityId");
				if(StringUtil.isEmpty(id)) throw new Exception("参数为空");
				EtlEntity entity = service.getById(Integer.valueOf(id));

				if (request.getMethod().equalsIgnoreCase("get")) {
					request.setAttribute("entity", entity);
					request.getRequestDispatcher("/jsp/etl/update.jsp").forward(request, response);
					return;
				}

				ServletUtils.updateEntity(request, entity);
				entity.setUpdateDate(new Timestamp(System.currentTimeMillis()));
				service.update(entity);
			} catch (Exception e) {
				logger.error("更新操作失败", e);
				request.setAttribute("error", e.getMessage());
				request.getRequestDispatcher("/jsp/error.jsp").forward(request, response);
				return;
			}	
			response.sendRedirect(request.getContextPath()+"/manage/etl?act=getPage");
		}
		
		/**
		 * 删除
		 * @param request
		 * @param response
		 * @return
		 */
		public void delete(HttpServletRequest request, HttpServletResponse response){
			String message = null;
			try {
				String id = request.getParameter("id");
				EtlEntity entity = service.getEntityByKey("entity_id", id);
				service.delete(entity);
			} catch (Exception e) {
				logger.error("删除操作失败", e);
				message = "{'code':0,'message':'"+e.getMessage()+"'}";
				ServletUtils.outputHTML(response,message);
				return;
			}	
			
			message = "{'code':1,'message':'删除成功'}";
			ServletUtils.outputHTML(response,message);
		}
		
		/**
		 * 查看
		 * @param request
		 * @param response
		 * @return
		 * @throws IOException 
		 * @throws ServletException 
		 */
		public void view(HttpServletRequest request, HttpServletResponse response) throws Exception{
			int entityId = HttpParamCaster.getIntParameter(request, "entityId", 0);
			String size = HttpParamCaster.getUTF8Parameter(request, "size");
			EtlEntity entity = service.getById(entityId);
			List<EtlScriptEntity> scriptList = scriptService.getList(entityId);
			List<EtlDependentEntity> depList = dependentService.getList(entityId);
			request.setAttribute("entity", entity);
			request.setAttribute("size", size);
			request.setAttribute("scriptList", scriptList);
			request.setAttribute("depList", depList);
			request.getRequestDispatcher("/jsp/etl/view.jsp").forward(request, response);
		}
				
}
